<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      26-结构体取代类 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>26-结构体取代类</h2>



  <p class="post-date">2019-03-10</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h2 id="Go-支持面向对象吗？"><a href="#Go-支持面向对象吗？" class="headerlink" title="Go 支持面向对象吗？"></a>Go 支持面向对象吗？</h2><p>Go 并不是完全面向对象的编程语言。Go 官网回答了 Go 是否是面向对象语言，摘录如下。</p>
<blockquote>
<p>可以说是，也可以说不是。虽然 Go 有类型和方法，支持面向对象的编程风格，但却没有类型的层次结构。Go  中的“接口”概念提供了一种不同的方法，我们认为它易于使用，也更为普遍。Go  也可以将结构体嵌套使用，这与子类化（Subclassing）类似，但并不完全相同。此外，Go 提供的特性比 C++ 或 Java  更为通用：子类可以由任何类型的数据来定义，甚至是内建类型（如简单的“未装箱的”整型）。这在结构体（类）中没有受到限制。</p>
</blockquote>
<p>在接下来的教程里，我们会讨论如何使用 Go 来实现面向对象编程概念。与其它面向对象语言（如 Java）相比，Go 有很多完全不同的特性。</p>
<h2 id="使用结构体，而非类"><a href="#使用结构体，而非类" class="headerlink" title="使用结构体，而非类"></a>使用结构体，而非类</h2><p>Go 不支持类，而是提供了[结构体]。结构体中可以添加[方法]。这样可以将数据和操作数据的方法绑定在一起，实现与类相似的效果。</p>
<p>为了加深理解，我们来编写一个示例吧。</p>
<p>在示例中，我们创建一个自定义[包]，它帮助我们更好地理解，结构体是如何有效地取代类的。</p>
<p>在你的 Go 工作区创建一个名为 <code>oop</code> 的文件夹。在 <code>opp</code> 中再创建子文件夹 <code>employee</code>。在 <code>employee</code> 内，创建一个名为 <code>employee.go</code> 的文件。</p>
<p>文件夹结构会是这样：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">workspacepath -&gt; oop -&gt; employee -&gt; employee.go</span><br></pre></td></tr></table></figure>

<p>请将 <code>employee.go</code> 里的内容替换为如下所示的代码。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> employee</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Employee <span class="keyword">struct</span> &#123;  </span><br><span class="line">    FirstName   <span class="keyword">string</span></span><br><span class="line">    LastName    <span class="keyword">string</span></span><br><span class="line">    TotalLeaves <span class="keyword">int</span></span><br><span class="line">    LeavesTaken <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e Employee)</span> <span class="title">LeavesRemaining</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    fmt.Printf(<span class="string">"%s %s has %d leaves remaining"</span>, e.FirstName, e.LastName, (e.TotalLeaves - e.LeavesTaken))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上述程序里，第 1 行指定了该文件属于 <code>employee</code> 包。而第 7 行声明了一个 <code>Employee</code> 结构体。在第 14 行，结构体 <code>Employee</code> 添加了一个名为 <code>LeavesRemaining</code> 的方法。该方法会计算和显示员工的剩余休假数。于是现在我们有了一个结构体，并绑定了结构体的方法，这与类很相似。</p>
<p>接着在 <code>oop</code> 文件夹里创建一个文件，命名为 <code>main.go</code>。</p>
<p>现在目录结构如下所示：  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">workspacepath -&gt; oop -&gt; employee -&gt; employee.go  </span><br><span class="line">workspacepath -&gt; oop -&gt; main.go</span><br></pre></td></tr></table></figure>

<p><code>main.go</code> 的内容如下所示：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"oop/employee"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    e := employee.Employee &#123;</span><br><span class="line">        FirstName: <span class="string">"Sam"</span>,</span><br><span class="line">        LastName: <span class="string">"Adolf"</span>,</span><br><span class="line">        TotalLeaves: <span class="number">30</span>,</span><br><span class="line">        LeavesTaken: <span class="number">20</span>,</span><br><span class="line">    &#125;</span><br><span class="line">    e.LeavesRemaining()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们在第 3 行引用了 <code>employee</code> 包。在 <code>main()</code>（第 12 行），我们调用了 <code>Employee</code> 的 <code>LeavesRemaining()</code> 方法。</p>
<p>由于有自定义包，这个程序不能在 go playground 上运行。你可以在你的本地运行，在 <code>workspacepath/bin/oop</code> 下输入命令 <code>go install opp</code>，程序会打印输出：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Sam Adolf has 10 leaves remaining</span><br></pre></td></tr></table></figure>

<h2 id="使用-New-函数，而非构造器"><a href="#使用-New-函数，而非构造器" class="headerlink" title="使用 New() 函数，而非构造器"></a>使用 New() 函数，而非构造器</h2><p>我们上面写的程序看起来没什么问题，但还是有一些细节问题需要注意。我们看看当定义一个零值的 <code>employee</code> 结构体变量时，会发生什么。将 <code>main.go</code> 的内容修改为如下代码：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"oop/employee"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    <span class="keyword">var</span> e employee.Employee</span><br><span class="line">    e.LeavesRemaining()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们的修改只是创建一个零值的 <code>Employee</code> 结构体变量（第 6 行）。该程序会输出：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">has 0 leaves remaining</span><br></pre></td></tr></table></figure>

<p>你可以看到，使用 <code>Employee</code> 创建的零值变量没有什么用。它没有合法的姓名，也没有合理的休假细节。</p>
<p>在像 Java 这样的 OOP 语言中，是使用构造器来解决这种问题的。一个合法的对象必须使用参数化的构造器来创建。</p>
<p>Go 并不支持构造器。如果某类型的零值不可用，需要程序员来隐藏该类型，避免从其他包直接访问。程序员应该提供一种名为 <code>NewT(parameters)</code> 的 [函数]，按照要求来初始化 <code>T</code> 类型的变量。按照 Go 的惯例，应该把创建 <code>T</code> 类型变量的函数命名为 <code>NewT(parameters)</code>。这就类似于构造器了。如果一个包只含有一种类型，按照 Go 的惯例，应该把函数命名为 <code>New(parameters)</code>， 而不是 <code>NewT(parameters)</code>。</p>
<p>让我修改一下原先的代码，使得每当创建 <code>employee</code> 的时候，它都是可用的。</p>
<p>首先应该让 <code>Employee</code> 结构体不可引用，然后创建一个 <code>New</code> 函数，用于创建 <code>Employee</code> 结构体变量。在 <code>employee.go</code> 中输入下面代码：  </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> employee</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> employee <span class="keyword">struct</span> &#123;  </span><br><span class="line">    firstName   <span class="keyword">string</span></span><br><span class="line">    lastName    <span class="keyword">string</span></span><br><span class="line">    totalLeaves <span class="keyword">int</span></span><br><span class="line">    leavesTaken <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">New</span><span class="params">(firstName <span class="keyword">string</span>, lastName <span class="keyword">string</span>, totalLeave <span class="keyword">int</span>, leavesTaken <span class="keyword">int</span>)</span> <span class="title">employee</span></span> &#123;  </span><br><span class="line">    e := employee &#123;firstName, lastName, totalLeave, leavesTaken&#125;</span><br><span class="line">    <span class="keyword">return</span> e</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e employee)</span> <span class="title">LeavesRemaining</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    fmt.Printf(<span class="string">"%s %s has %d leaves remaining"</span>, e.firstName, e.lastName, (e.totalLeaves - e.leavesTaken))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们进行了一些重要的修改。我们把 <code>Employee</code> 结构体的首字母改为小写 <code>e</code>，也就是将 <code>type Employee struct</code> 改为了 <code>type employee struct</code>。通过这种方法，我们把 <code>employee</code> 结构体变为了不可引用的，防止其他包对它的访问。除非有特殊需求，否则也要隐藏所有不可引用的结构体的所有字段，这是 Go 的最佳实践。由于我们不会在外部包需要 <code>employee</code> 的字段，因此我们也让这些字段无法引用。</p>
<p>同样，我们还修改了 <code>LeavesRemaining()</code> 的方法。</p>
<p>现在由于 <code>employee</code> 不可引用，因此不能在其他包内直接创建 <code>Employee</code> 类型的变量。于是我们在第 14 行提供了一个可引用的 <code>New</code> 函数，该函数接收必要的参数，返回一个新创建的 <code>employee</code> 结构体变量。</p>
<p>这个程序还需要一些必要的修改，但现在先运行这个程序，理解一下当前的修改。如果运行当前程序，编译器会报错，如下所示：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">go/src/constructor/main.go:6: undefined: employee.Employee</span><br></pre></td></tr></table></figure>

<p>这是因为我们将 <code>Employee</code> 设置为不可引用，因此编译器会报错，提示该类型没有在 <code>main.go</code> 中定义。很完美，正如我们期望的一样，其他包现在不能轻易创建零值的 <code>employee</code> 变量了。我们成功地避免了创建不可用的 <code>employee</code> 结构体变量。现在创建 <code>employee</code> 变量的唯一方法就是使用 <code>New</code> 函数。</p>
<p>如下所示，修改 <code>main.go</code> 里的内容。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main  </span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"oop/employee"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    e := employee.New(<span class="string">"Sam"</span>, <span class="string">"Adolf"</span>, <span class="number">30</span>, <span class="number">20</span>)</span><br><span class="line">    e.LeavesRemaining()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>该文件唯一的修改就是第 6 行。通过向 <code>New</code> 函数传入所需变量，我们创建了一个新的 <code>employee</code> 结构体变量。</p>
<p>下面是修改后的两个文件的内容。</p>
<p>employee.go</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> employee</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (  </span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> employee <span class="keyword">struct</span> &#123;  </span><br><span class="line">    firstName   <span class="keyword">string</span></span><br><span class="line">    lastName    <span class="keyword">string</span></span><br><span class="line">    totalLeaves <span class="keyword">int</span></span><br><span class="line">    leavesTaken <span class="keyword">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">New</span><span class="params">(firstName <span class="keyword">string</span>, lastName <span class="keyword">string</span>, totalLeave <span class="keyword">int</span>, leavesTaken <span class="keyword">int</span>)</span> <span class="title">employee</span></span> &#123;  </span><br><span class="line">    e := employee &#123;firstName, lastName, totalLeave, leavesTaken&#125;</span><br><span class="line">    <span class="keyword">return</span> e</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(e employee)</span> <span class="title">LeavesRemaining</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    fmt.Printf(<span class="string">"%s %s has %d leaves remaining"</span>, e.firstName, e.lastName, (e.totalLeaves - e.leavesTaken))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>main.go</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main  </span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">"oop/employee"</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;  </span><br><span class="line">    e := employee.New(<span class="string">"Sam"</span>, <span class="string">"Adolf"</span>, <span class="number">30</span>, <span class="number">20</span>)</span><br><span class="line">    e.LeavesRemaining()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行该程序，会输出：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Sam Adolf has 10 leaves remaining</span><br></pre></td></tr></table></figure>

<p>现在你能明白了，虽然 Go 不支持类，但结构体能够很好地取代类，而以 <code>New(parameters)</code> 签名的方法可以替代构造器。</p>
</section>
    <!-- Tags START -->
    
      <div class="tags">
        <span>Tags:</span>
        
  <a href="/tags#Go" >
    <span class="tag-code">Go</span>
  </a>

      </div>
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/go/2-Go%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80/25-Mutex/">
        <span class="nav-arrow">← </span>
        
          25-Mutex
        
      </a>
    
    
      <a class="nav-right" href="/go/2-Go%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80/23-%E7%BC%93%E5%86%B2%E4%BF%A1%E9%81%93%E5%92%8C%E5%B7%A5%E4%BD%9C%E6%B1%A0/">
        
          23. 缓冲信道和工作池（Buffered Channels and Worker Pools）
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#Go-支持面向对象吗？"><span class="toc-nav-text">Go 支持面向对象吗？</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#使用结构体，而非类"><span class="toc-nav-text">使用结构体，而非类</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#使用-New-函数，而非构造器"><span class="toc-nav-text">使用 New() 函数，而非构造器</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/go/2-Go语言基础/26-结构体取代类/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "26-结构体取代类",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>